package com.xhwl.centiotdata.handler.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.handler.alarm.AlarmFactory;
import com.xhwl.centiotdata.handler.alarm.AlarmHandler;
import com.xhwl.centiotdata.mq.producer.GeneralProducer;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.centiotdata.utils.SpringContextUtils;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.alarm.haikang.HaiKangEventsBody;
import com.xhwl.common.dto.cent.alarm.haikang.HaiKangJson;
import com.xhwl.common.dto.cent.alarm.haikang.HaiKangParamsBody;
import com.xhwl.common.dto.cent.alarm.haikang.VariableJson;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.alarm.AlarmLog;
import com.xhwl.common.pojo.cent.alarm.AlarmManagement;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Leon
 * @Description: TODO
 * @Date: 2022/5/9 14:15
 */
@Component
@Slf4j
public class HaiKangReceiveHandler extends AlarmHandler {

    @Override
    public void afterPropertiesSet() throws Exception {
        // AlarmFactory.register("HaiKangReceive",this); //todo 暂时不注入也可
    }

    public ResultJson haiKangReceive(String haiKangReceive, Integer projectId) {
        log.info("海康平台返回的json数据示例======================>{}", haiKangReceive);
        AlarmLog alarmLog = new AlarmLog();
        alarmLog.setTag("iot-HaiKang");
        alarmLog.setContent(haiKangReceive);
        alarmLog.setPushTime(new Date());
        centAlarmService.insert(alarmLog);
        HaiKangJson haiKangJson = parseObject(haiKangReceive, HaiKangJson.class);
        HaiKangParamsBody params = haiKangJson.getParams();
        List<HaiKangEventsBody> events = params.getEvents();

        Map<String, String> entries = redisTemplate.opsForHash().entries(RedisUtils.format(2));

        events.forEach(item -> {
            if (StringUtils.isNotBlank(Optional.ofNullable(item.getEventDetails())
                    .map(Object::toString).orElse(""))) {
                List<HaiKangEventsBody> inner = JSONObject.parseArray(JSONObject.toJSONString(item.getEventDetails()), HaiKangEventsBody.class);
                inner.forEach(echo -> {
                    DevicePageQuery devicePageQuery = new DevicePageQuery();
                    devicePageQuery.setThirdDeviceIdList(Arrays.asList(echo.getSrcIndex()));
                    Page<DeviceDTO> deviceDTOPage = deviceCentService.pageDevice(null, devicePageQuery);

                    if (CollectionUtils.isNotEmpty(deviceDTOPage.getRecords())) {
                        if (StringUtils.isNotBlank(entries.get(echo.getEventType()))) {
                            AlarmManagement alarmManagement = new AlarmManagement();
                            alarmManagement.setAlarmTime(Date.from(item.getHappenTime().atZone(ZoneId.systemDefault()).toInstant()));
                            alarmManagement.setDeviceId(Optional.ofNullable(deviceDTOPage.getRecords())
                                    .map(unit -> unit.get(0).getId()).orElse(null));
                            alarmManagement.setAlarmInventoryCode(entries.get(echo.getEventType()));
                            sendMq(AlarmConstant.HAIKANG_ALARM_TOPIC, alarmManagement);
                        }
                    }
                });
            } else {
                DevicePageQuery devicePageQuery = new DevicePageQuery();
                devicePageQuery.setProductId(2);
                devicePageQuery.setProjectId(projectId);
                devicePageQuery.setThirdDeviceIdList(Arrays.asList(item.getSrcIndex()));
                Page<DeviceDTO> deviceDTOPage = deviceCentService.pageDevice(null, devicePageQuery);

                if (CollectionUtils.isNotEmpty(deviceDTOPage.getRecords())) {
                    if (StringUtils.isNotBlank(entries.get(item.getEventType()))) {
                        AlarmManagement alarmManagement = new AlarmManagement();
                        alarmManagement.setAlarmTime(Date.from(item.getHappenTime().atZone(ZoneId.systemDefault()).toInstant()));
                        alarmManagement.setDeviceId(Optional.ofNullable(deviceDTOPage.getRecords())
                                .map(unit -> unit.get(0).getId()).orElse(null));
                        if (Objects.nonNull(item.getData())) {
                            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(item.getData()));
                            String imageUrl = Optional.ofNullable(jsonObject).map(unit -> unit.getString("eventDescription")).map(unit ->
                                    JSONObject.parseArray(jsonObject.getString(unit), VariableJson.class)
                            ).map(unit -> unit.get(0)).map(VariableJson::getImageUrl).orElse("");

                            //todo  此处解决中建信合城问题 大坑
                            if (42 == Optional.ofNullable(deviceDTOPage.getRecords())
                                    .filter(unit -> CollectionUtils.isNotEmpty(unit))
                                    .map(unit -> unit.get(0).getProjectId()).orElse(null)) {
                                alarmManagement.setImgUrl(imageUrl.replace("http://192.168.131.40", "https://cent.xhmind.com"));
                            } else {
                                alarmManagement.setImgUrl(imageUrl);
                            }
                        }
                        alarmManagement.setAlarmInventoryCode(entries.get(item.getEventType()));
                        sendMq(AlarmConstant.HAIKANG_ALARM_TOPIC, alarmManagement);
                    }
                }
            }
        });
        return ResultJson.success();
    }


    public ResultJson haiKangReceiveConfig(String haiKangReceive, Integer rowId) {
        log.info("====收到 海康ISC 告警消息 ===: {}, rowId: {}", haiKangReceive, rowId);
        return ResultJson.success();
    }

}

